package cn.tx.erp.sys.controller;

import cn.tx.erp.sys.domain.Permission;
import cn.tx.erp.sys.domain.Role;
import cn.tx.erp.sys.service.PermissionService;
import cn.tx.erp.sys.service.RoleService;
import cn.tx.erp.sys.tree.TreeNode;
import cn.tx.erp.sys.utils.Constast;
import cn.tx.erp.sys.utils.DataGridView;
import cn.tx.erp.sys.utils.ResultObj;
import cn.tx.erp.sys.vo.RoleVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 角色管理
 * @author Mxb
 * @version 1.0
 * @date 2020/7/11 18:14
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 查询加载所有角色
     * @param roleVo
     * @return
     */
    @RequestMapping(value = "/loadAllRole", method = RequestMethod.GET)
    public DataGridView loadAllRole(RoleVo roleVo) {
        //开启分页
        IPage<Role> page = new Page<>(roleVo.getPage(), roleVo.getLimit());

        QueryWrapper<Role> qw = new QueryWrapper<>();
        qw.like(StringUtils.isNotBlank(roleVo.getName()), "name", roleVo.getName());
        qw.like(StringUtils.isNotBlank(roleVo.getRemark()), "remark", roleVo.getRemark());

        qw.eq(roleVo.getAvailable() != null, "available", roleVo.getAvailable());
        qw.orderByDesc("createtime");

        this.roleService.page(page, qw);
        return new DataGridView(0, "成功", page.getTotal(), page.getRecords());
    }

    /**
     * 添加角色
     * @param roleVo
     * @return
     */
    @RequestMapping(value = "/addRole")
    public ResultObj addRole(RoleVo roleVo) {
        try {
            roleVo.setCreatetime(new Date());
            this.roleService.save(roleVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            return ResultObj.ADD_ERR;
        }
    }

    /**
     * 更新角色
     * @param roleVo
     * @return
     */
    @RequestMapping(value = "/updateRole")
    public ResultObj updateRole(RoleVo roleVo) {
        try {
            this.roleService.updateById(roleVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            return ResultObj.UPDATE_ERR;
        }
    }


    /**
     * 删除角色
     * @param roleVo
     * @return
     */
    @RequestMapping(value = "/deleteRole")
    public ResultObj deleteRole(RoleVo roleVo) {
        try {
            this.roleService.removeById(roleVo.getId());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            return ResultObj.DELETE_ERR;
        }
    }

    /**
     * 根据角色ID 加载菜单和权限的树的 json串
     * @param roleId
     * @return
     */
    @RequestMapping("/initPermissionByRoleId")
    public DataGridView initPermissionByRoleId(Integer roleId) {
        // 查询所有可用的菜单和权限
        QueryWrapper<Permission> qw = new QueryWrapper<>();
        qw.eq("available", Constast.AVAILABLE_TRUE); //1
        List<Permission> allPermissionList = permissionService.list(qw);

        //根据角色id 查询当前角色拥有的权限和菜单
        // 连表
        // 不连表 怎么做  根据角色id 查询到 拥有权限或菜单id的 集合
        // 根据 权限或菜单id ，查询 权限信息
        List<Integer> permissionIdList = this.roleService.queryRolePermissionByRid(roleId);

        List<Permission> carrentPermissions = null;

        if (permissionIdList.size() > 0) {
            // id 不为空
            qw.in("id", permissionIdList);
            carrentPermissions = this.permissionService.list(qw);
        } else {
            carrentPermissions = new ArrayList<>();
        }
        //构造 List<TreeNode>树
        List<TreeNode> nodes = new ArrayList<>();
        // 遍历所有的 权限
        for (Permission p1 : allPermissionList) {
            String checkArr = "0";
            for (Permission p2 : carrentPermissions) {
                // 2个id相等 改为选中状态
                if (p1.getId() == p2.getId()) {
                    checkArr = "1";
                    break;
                }
            }
            Boolean spread = (p1.getOpen() == null || p1.getOpen() == 1) ? true : false;
            nodes.add(new TreeNode(p1.getId(), p1.getPid(), p1.getTitle(), spread, checkArr));
        }
        return new DataGridView(nodes);
    }

    /**
     * 保存角色和菜单权限之间的关系
     */
    @RequestMapping("saveRolePermission")
    public ResultObj saveRolePermission(Integer rid, Integer[] ids) {
        try {
            this.roleService.saveRolePermission(rid, ids);
            return ResultObj.DIS_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DIS_ERR;
        }
    }
}
